package org.gd.hellojaxb.example.map;

import org.gd.hellojaxb.utils.MarshallProperties;
import org.gd.hellojaxb.utils.Marshall;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.Map;
import java.util.TreeMap;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "map")
public class XmlStringMap extends TreeMap<String, String> {

    public XmlStringMap() {
        super();
    }

    public XmlStringMap(Map<?, ?> map) {
        this();
        put(map);
    }

    @SuppressWarnings("unused")
    @Deprecated
    public String nPut(Object key, Object value) {
        return super.put(key.toString(), value.toString());
    }

    public void put(Map<?, ?> m) {
        for (Map.Entry<?, ?> entry : m.entrySet()) {
            put(entry.getKey().toString(), entry.getValue().toString());
        }
    }

    @XmlElement(name = "map")
    @XmlJavaTypeAdapter(MapAdaptersFactory.StringStringMapAdapter.class)
    @SuppressWarnings("unused")
    public Map<String, String> getThis() {
        return this;
    }



    @Override
    public String toString() {
        try {
            return Marshall.getInstance().marshal(this,
                    MarshallProperties.WITH_XML_HEADER,
                    MarshallProperties.FORMATTED_OUTPUT
            );
        } catch (Throwable e) {
            //e.printStackTrace(System.err);
            System.err.println(e.toString());
            return super.toString();
        }
    }
}
